package com.pinhuba.bams.view;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.pinhuba.bams.R;
import com.pinhuba.bams.framework.ConfigProperties;
import com.pinhuba.bams.framework.ErrorCode;
import com.pinhuba.bams.framework.UrlType;
import com.pinhuba.bams.framework.controller.Controller;
import com.pinhuba.bams.framework.controller.ErrorListener;
import com.pinhuba.bams.framework.Params;
import com.pinhuba.bams.framework.util.JsonHandle;
import com.pinhuba.bams.framework.util.Loger;
import com.pinhuba.bams.framework.util.ParseXmlService;
import com.pinhuba.bams.framework.util.SharePrefsHelper;
import com.pinhuba.bams.framework.util.Version;

public class MainActivity extends Activity {
	private TextView name;

	private ImageView dbgz;
	private ImageView dygz;
	private ImageView gzcx;
	private ImageView tzgg;
	private ImageView xwzx;
	private ImageView wdyj;
	private ImageView ztdt;
	private ImageView txl;

	private SharePrefsHelper spHelper;
	private ArrayList<HashMap<String, Integer>> imageItems;

	private Timer tm = null;
	private TimerTask task = null;
	private TimerTask taskUpdate = null;
	private String versionName;
	private String versionDescription;
	private String versionURL;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initView();
		initData();
		setListener();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (tm != null) {
			tm.cancel();
			tm = null;
		}

		if (task != null) {
			task.cancel();
			task = null;
		}
		if (taskUpdate != null) {
			task.cancel();
			task = null;
		}
	}

	void initView() {
		name = (TextView) findViewById(R.id.name);
		dbgz = (ImageView) findViewById(R.id.dbgz);
		dygz = (ImageView) findViewById(R.id.dygz);
		gzcx = (ImageView) findViewById(R.id.gzcx);
		tzgg = (ImageView) findViewById(R.id.tzgg);
		xwzx = (ImageView) findViewById(R.id.xwzx);
		wdyj = (ImageView) findViewById(R.id.wdyj);
		ztdt = (ImageView) findViewById(R.id.ztdt);
		txl = (ImageView) findViewById(R.id.txl);
		imageItems = new ArrayList<HashMap<String, Integer>>();
	}

	void initData() {
		// 获取最近登录的人员
		name.setText(new SharePrefsHelper(getApplicationContext()).getLastestUserName());

		spHelper = new SharePrefsHelper(this);

		int icon[] = { R.drawable.dbgz, R.drawable.dygz, R.drawable.gzcx, R.drawable.tzgg, R.drawable.xwzx, R.drawable.wdyj, R.drawable.ztdt, R.drawable.txl };

		for (int i = 0; i < 8; i++) {
			HashMap<String, Integer> hm = new HashMap<String, Integer>();
			hm.put("itemImage", icon[i]);
			imageItems.add(hm);
		}

		startHttpGetSessionId();
		doUpdateRequest();
	}

	int i = 0;

	private void startHttpGetSessionId() {
		if (tm == null) {
			tm = new Timer(true);
		}
		if (task == null) {
			task = new TimerTask() {
				@Override
				public void run() {
					i++;
					Controller.getInstance().doRequest(MainActivity.this, UrlType.LOGINCHECK, getSessionIdErrorListener,
							Params.login(spHelper.getLastestUserLoginAccount(), spHelper.getLastestUserLoginPwd()));
				}
			};
		}
		tm.schedule(task, 29 * 60 * 1000, 29 * 60 * 1000);// 据说是SessionId周期的是30分钟
															// 这里有些问题吧
	}

	private void doUpdateRequest() {
		taskUpdate = new TimerTask() {

			@Override
			public void run() {
				checkUpdate();
			}
		};
		tm.schedule(taskUpdate, 2 * 1000);
	}

	void checkUpdate() {
		// Send UPdate request
		String strResult = "";
		boolean isSuccess = false;
		HttpClient httpclient = null;
		try {
			HttpGet httpRequest = new HttpGet(ConfigProperties.UPDATE_URL);
			// 取得HttpClient对象
			httpclient = new DefaultHttpClient();
			// 请求HttpClient，取得HttpResponse
			HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), ConfigProperties.TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpclient.getParams(), ConfigProperties.TIMEOUT);
			HttpResponse httpResponse = httpclient.execute(httpRequest);
			// 请求成功
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 取得返回的字符串
				// strResult = EntityUtils.toString(httpResponse.getEntity());
				strResult = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
				Loger.d("PML" + strResult);
				isSuccess = true;
			} else {
				isSuccess = false;
				Loger.d("Wrong");
			}
		} catch (ConnectTimeoutException e) {
			e.getStackTrace();
			isSuccess = false;
		} catch (SocketTimeoutException e) {
			e.getStackTrace();
			isSuccess = false;
		} catch (IOException e) {
			e.getStackTrace();
			isSuccess = false;
		} catch (ParseException e) {
			e.getStackTrace();
			isSuccess = false;
		} finally {
			if (httpclient != null) {
				httpclient.getConnectionManager().shutdown();
			}
			if (isSuccess) {
				handleUpdateRequestData(strResult);
			}
		}
	}

	private void handleUpdateRequestData(String strResult) {

		strResult = strResult.replace("&", "&amp;");
		ParseXmlService ps = new ParseXmlService();
		InputStream Is = null;
		HashMap<String, String> hm = new HashMap<String, String>();
		String StartSign = "<versionInfo>";
		String EndSign = "</versionInfo>";
		String UpdateData = strResult.substring(strResult.indexOf(StartSign), strResult.indexOf(EndSign) + EndSign.length());

		Loger.e("UpdateData is:" + UpdateData);
		if (UpdateData != null && !UpdateData.equals("")) {
			Is = new ByteArrayInputStream(UpdateData.getBytes());
			try {
				hm = ps.parseXml(Is);
				Loger.d(hm.get("versionCode") + ";" + hm.get("versionName"));
				int newVersionCode = Integer.parseInt(hm.get("versionCode").toString());
				int oldVersionCode = Version.getVersionCode();
				if (newVersionCode > oldVersionCode) {
					versionName = hm.get("versionName").toString();
					versionDescription = hm.get("versionDescription").toString();
					versionURL = hm.get("versionURL").toString();
					activityForward();
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void activityForward() {
		Intent it = new Intent(MainActivity.this, UpdateActivity.class);
		it.putExtra("versionName", versionName);
		it.putExtra("versionDescription", versionDescription);
		it.putExtra("versionURL", versionURL);
		startActivity(it);
	}

	private ErrorListener getSessionIdErrorListener = new ErrorListener() {

		@Override
		public void onSuccess(UrlType api, String json) {
			try {
				Loger.d("PML" + i + "Json is:" + json);
				JSONObject LoginJson = new JSONObject(json);
				if (JsonHandle.getInstance().jsonCodeHandle(LoginJson) == 0) {
					String SessionId = LoginJson.getString("SessionId").trim();
					Params.setUserSessionId(SessionId);
				}
			} catch (JSONException e) {

			} finally {

			}
		}

		@Override
		public void onError(UrlType api, ErrorCode code) {

		}
	};

	void setListener() {

		OnClickListener mainImageClickListener = new OnClickListener() {

			@Override
			public void onClick(View view) {
				Intent it = new Intent();
				switch (view.getId()) {
				case R.id.dbgz:
					it.setClass(MainActivity.this, AnnounceListActivity.class);
					break;
				case R.id.dygz:
					it.setClass(MainActivity.this, AnnounceListActivity.class);
					break;
				case R.id.gzcx:
					it.setClass(MainActivity.this, AnnounceListActivity.class);
					break;
				case R.id.tzgg:
					it.setClass(MainActivity.this, AnnounceListActivity.class);
					break;
				case R.id.xwzx:
					it.setClass(MainActivity.this, AnnounceListActivity.class);
					break;
				case R.id.wdyj:
					it.setClass(MainActivity.this, AnnounceListActivity.class);
					break;
				case R.id.ztdt:
					it.setClass(MainActivity.this, AnnounceListActivity.class);
					break;
				case R.id.txl:
					it.setClass(MainActivity.this, AnnounceListActivity.class);
					break;

				default:
					break;
				}
				startActivity(it);
			}
		};

		dbgz.setOnClickListener(mainImageClickListener);
		dygz.setOnClickListener(mainImageClickListener);
		gzcx.setOnClickListener(mainImageClickListener);
		tzgg.setOnClickListener(mainImageClickListener);
		xwzx.setOnClickListener(mainImageClickListener);
		wdyj.setOnClickListener(mainImageClickListener);
		ztdt.setOnClickListener(mainImageClickListener);
		txl.setOnClickListener(mainImageClickListener);
	}

	private class mainGridViewAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return imageItems.size();
		}

		@Override
		public Object getItem(int index) {
			return imageItems.get(index);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		private class MainHolder {
			ImageView img;
		}

		@Override
		public View getView(int position, View view, ViewGroup arg2) {
			MainHolder holder;
			if (view == null) {
				holder = new MainHolder();
				view = LayoutInflater.from(MainActivity.this).inflate(R.layout.main_item, null);
				holder.img = (ImageView) view.findViewById(R.id.imageview);
				view.setTag(holder);
			} else {
				holder = (MainHolder) view.getTag();
			}

			holder.img.setImageResource(imageItems.get(position).get("itemImage"));
			return view;
		}

	}

	private void showExitDialog() {
		// 弹出确定退出对话框
		new AlertDialog.Builder(this).setTitle(R.string.exit).setMessage(R.string.confirm_exit).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (tm != null) {
					tm.cancel();
					tm = null;
				}

				if (task != null) {
					task.cancel();
					task = null;
				}
				Intent exit = new Intent(Intent.ACTION_MAIN);
				exit.addCategory(Intent.CATEGORY_HOME);
				exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(exit);
				System.exit(0);
			}
		}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		}).show();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showExitDialog();
			// 这里不需要执行父类的点击事件，所以直接return
			return true;
		}
		// 继续执行父类的其他点击事件
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 1, R.string.setting).setIcon(R.drawable.menu_sys_opt);
		menu.add(0, 2, 1, R.string.logout).setIcon(R.drawable.menu_logout);
		menu.add(0, 3, 1, R.string.helpupdate).setIcon(R.drawable.help_menu_icon);
		menu.add(0, 4, 1, R.string.exitsystem).setIcon(R.drawable.exit_menu_icon);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			Intent SettingIntent = new Intent(MainActivity.this, PreferenceSettingActivity.class);
			this.startActivity(SettingIntent);
			break;
		case 2:
			logout();
			break;
		case 3:
			helpUpdate();
			break;
		case 4:
			showExitDialog();
			break;
		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	private void logout() {
		if (tm != null) {
			tm.cancel();
			tm = null;
		}

		if (task != null) {
			task.cancel();
			task = null;
		}
		if (taskUpdate != null) {
			taskUpdate.cancel();
			taskUpdate = null;
		}
		spHelper.setIfAutoLogin(false);
		spHelper.setIfSavePwd(false);
		spHelper.setLastestLoginPwd("");
		spHelper.setLastestUserName("");

		Intent it = new Intent(MainActivity.this, LoginActivity.class);
		startActivity(it);
		this.finish();
	}

	private void helpUpdate() {
		Intent it = new Intent(MainActivity.this, HelpUpdateActivity.class);
		startActivity(it);
	}

}
